package com.chen.authority.common.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chen.authority.common.annotation.Query;

import java.lang.reflect.Field;

/**
 * 查询包装器 工具类
 *
 * @author chengy
 * @date 2023/11/20
 */
public class WrapperUtil {

    /**
     * 构建函数查询包装器
     *
     * @param qo 查询对象
     * @return 函数查询包装器
     */
    @SuppressWarnings("unchecked")
    public static <T> LambdaQueryWrapper<T> buildLambdaQueryWrapper(Object qo) {
        return (LambdaQueryWrapper<T>) buildQueryWrapper(qo).lambda();
    }

    /**
     * 构建查询包装器
     *
     * @param qo 查询对象
     * @return 查询包装器
     */
    public static <T> QueryWrapper<T> buildQueryWrapper(Object qo) {
        QueryWrapper<T> queryWrapper = Wrappers.query();
        if (BeanUtil.isNotEmpty(qo)) {
            Field[] fields = qo.getClass().getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                Query query = field.getAnnotation(Query.class);
                if (ObjectUtil.isNotNull(query)) {
                    try {
                        Object value = field.get(qo);
                        setQueryCondition(value, query, queryWrapper);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return queryWrapper;
    }

    /**
     * 设置查询条件
     *
     * @param value        值
     * @param query        查询注解
     * @param queryWrapper 查询包装器
     */
    private static <T> void setQueryCondition(Object value, Query query, QueryWrapper<T> queryWrapper) {
        if (ObjectUtil.isNotEmpty(value)) {
            switch (query.type()) {
                case LIKE:
                    queryWrapper.like(query.column(), value);
                    break;
                case EQ:
                    queryWrapper.eq(query.column(), value);
                    break;
                case GE:
                    queryWrapper.ge(query.column(), value);
                    break;
                case LE:
                    queryWrapper.le(query.column(), value);
                    break;
            }
        }
    }

}